layui.use(['form', 'layedit', 'laydate'], function () {
    var form = layui.form,
        layer = layui.layer,
        layedit = layui.layedit,
        laydate = layui.laydate;

    //日期
    laydate.render({
        elem: '#birthday',
        //    强制显示
        trigger: 'click'
    });
    form.render();

    findById();
//    页面加载完成，通过id去查询数据库，并将得到的数据，回显到页面
//    查询
    function findById() {
        let id = sessionStorage.getItem("userId");
        let res = myAjax("/back/user/findById", {id: id}, "get");
        console.log(res);
        if (res != null) {
            setUserData(res.data);
        }
    }

    //表单赋值
    //赋值
    function setUserData(data) {
        //layui普通表单赋值
        form.val('userEdit', {
            // "username": data.name, // "name": "value"
            "phone": data.phone,
            "sex": data.sex,
            "birthday": data.birthday
        });
        //jquery普通表单赋值
        $("#username").val(data.name);
        //单选框赋值
        $('input[type=radio][name=enable][value=' + data.enable + ']').attr("checked", "checked");
        //拿到数据库里面爱好，并将爱好转换为字符串数组
        let arr = data.hobby.split(",");
        $('input[type=checkbox][name=hobby]').each(function () {

            for (let i = 0; i < arr.length; i++) {
                if (arr[i] == $(this).attr("title")) {
                    $(this).attr("checked", "checked");
                }
            }

        });
        form.render();
    }

//    对按钮进行监听
    form.on('submit(edit)', function (data) {
        data = data.field;
        let arr = [];
        $('input[type=checkbox][name=hobby]:checked').each(function () {
            //$(this).val()表示拿到里面的值
            //如果要拿到属性值用attr
            arr.push($(this).attr("title"));
        });
        //arr.toLocaleString()将数组转换为字符串
        data.hobby = arr.toLocaleString();
        data.id = sessionStorage.getItem("userId");
        console.log(data);
        let res = myAjax("/back/user/update", data, "post");
        if (res.count > 0) {
            layer.alert("编辑成功", {
                    icon: 6
                },
                function () {
                    //关闭当前frame
                    xadmin.close();

                    // 可以对父窗口进行刷新
                    xadmin.father_reload();
                });
        } else {
            layer.alert("编辑失败");
        }

        return false;
    })

})